<?php

/**
 * 多级返佣模型
 */
class OrderRebate extends Model
{

    /**
     * @param $orderId
     */
    public function rebate($orderId) {
        $this->loadModel('mOrder');
        $orderInfo = $this->mOrder->getOrderInfo($orderId, false);
        // 避免重复
        if ($orderInfo && $orderInfo['rebated'] == 0) {
            $this->Db->transtart();
            try {
                # var_dump($orderInfo);
                $uidTop = intval($orderInfo['client_id']);
                // 返佣总金额
                $rebateAmount = floatval($orderInfo['order_amount']);
                # echo $rebateAmount . '<br />';
                $fields      = ['a1', 'a2', 'a3', 'a4', 'a5', 'a6', 'a7', 'a8', 'a9', 'a10'];
                $filedsWhere = [];
                foreach ($fields as $f) {
                    $filedsWhere[$f] = $uidTop;
                }
                // 获取上级
                $tree = $this->Dao->select()->from(TABLE_USER_TREES)->where($filedsWhere, false, 'OR')->getOneRow();

                if (sizeof($tree) > 0) {
                    // 查到对应上级数据
                    $rebateLevel = intval($this->settings['rebate_level']);
                    // 返佣级别设置
                    $rebateLevelData = $this->settings['rebate_level_data'];
                    // 返佣参数
                    if (!empty($rebateLevelData)) {
                        $rebateLevelData = explode(',', $rebateLevelData);
                    }
                    if ($rebateLevel > 0 && sizeof($rebateLevelData) == $rebateLevel) {
                        $rebateResult = [];
                        $rebateSize   = sizeof($fields);
                        // 查找返佣起点
                        for ($i = $rebateSize; $i > 0; $i--) {
                            if ($tree['a' . $i] == $uidTop) {
                                // 计算返佣数据
                                $i--;
                                // 返佣模式
                                $rebateWays = [
                                    'rebateLadder',
                                    'weightRebate'
                                ];
                                // todo 后台选择返佣模式
                                $rebateWay    = $rebateWays[0];
                                $rebateResult = $this->$rebateWay($tree, $rebateLevel, $rebateLevelData, $rebateAmount, $i);
                                break;
                            }
                        }
                        // 写入返佣数据
                        foreach ($rebateResult as $result) {
                            $result['uid']     = $uidTop;
                            $result['rtime']   = Util::getNOW();
                            $result['status']  = 'wait';
                            $result['orderid'] = $orderId;
                            $this->Dao->insert(TABLE_ORDER_REBATE, array_keys($result))->values(
                                $result
                            )->exec();
                        }
                        $this->Dao->update(TABLE_ORDERS)->set([
                            'rebated' => 1
                        ])->where('order_id = ' . $orderId)->exec();
                    }
                    // var_dump($rebateLevel);
                }
                // var_dump($tree);

                $this->Db->transcommit();
                return true;

            } catch (Exception $e) {

                Util::log($e->getMessage());
                $this->Db->transrollback();
                return false;

            }
        } else {
            return false;
        }
    }

    /**
     * 阶梯返佣
     * @param $tree
     * @param $rebateLevel
     * @param $rebateLevelData
     * @param $rebateAmount
     * @param $i
     * @return array
     */
    private function rebateLadder($tree, $rebateLevel, $rebateLevelData, $rebateAmount, $i) {
        $return = [];
        // 返佣算法
        for ($j = 0; $j < $rebateLevel; $j++) {
            // 阶梯返佣
            $rebateAmount *= $rebateLevelData[$j];
            $comid = intval($tree['a' . $i--]);
            if ($comid > 0) {
                $return[] = [
                    'comid' => $comid,
                    'rate' => floatval($rebateLevelData[$j]),
                    'amount' => floatval($rebateAmount)
                ];
            }
            # echo $tree['a' . $i--] . ' ' . $rebateLevelData[$j] . ' ' . $rebateAmount . '<br />';
        }
        return $return;
    }

    /**
     * 加权返佣
     * @param $tree
     * @param $rebateLevel
     * @param $rebateLevelData
     * @param $rebateAmount
     * @param $i
     * @todo
     */
    private function weightRebate($tree, $rebateLevel, $rebateLevelData, $rebateAmount, $i) {

    }

}